// pages/my/preferentialCenter/preferentialCenter.ts
// @ts-ignore
import { getACouponAvailable, getAlreadyOwnedCoupons, receiveACoupon } from '../../../http/api/couponService'
import Toast from 'tdesign-miniprogram/toast/index'

const tokenMixin = require('../../../mixin/tokenMixin')
//引入computed
const computedBehavior = require('miniprogram-computed')
Page({
    behaviors: [tokenMixin, computedBehavior],
    /**
     * 页面的初始数据
     */
    data: {
        valueArr: [
            {
                label: '可领取',
                value: 0
            },
            {
                label: '未使用',
                value: 1
            },
            {
                label: '已使用',
                value: 2
            },
            {
                label: '已失效',
                value: 3
            }
        ],
        type: 0, // 判断是否是首页进来到
        value: 0,
        showRule: false,
        confirmBtn: { content: '知道了', variant: 'base' },
        list: [],
        descObj: {},
        page: 1,
        size: 5,
        total: 0,
        isAll: false, // 判断是否没数据了
        all_money: null
    } as any,

    async use(e: any) {
        const obj = e.target.dataset.obj
        console.log(obj)
        if (this.data.type == 0) {
            const { list, value } = this.data
            if (value == 0) {
                const index = list.findIndex((item: any) => item.id == obj.id)
                console.log(index)
                // 可重复领取
                const res: any = await receiveACoupon(obj.id)
                console.log(res, ',,,,res')
                if (res[0].msg == '领劵成功') {
                    Toast({
                        context: this,
                        selector: '#t-toast',
                        message: '领劵成功'
                    })
                    if (list[index].receive == 1 && !list[index].isGet) {
                        list[index].number--
                        this.setData({
                            list: list
                        })
                    }
                }
            } else {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }
        } else {
            const { list } = this.data
            const index = list.findIndex((item: any) => item.id == obj.id)
            const info = obj.info
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2] //上一个页面
            prevPage.setData({
                coupon: `满${info.moneyStart}减${info.num}`,
                couponInfo: list[index]
            })
            wx.navigateBack()
        }
    },

    async onChange(e: any) {
        this.setData({
            value: e.detail.value,
            page: 1,
            total: 0
        })
        const { value } = this.data
        if (value === 0) {
            const arr = await this.getAccessCoupons(this.data.page, this.data.size)
            this.setData({
                list: arr
            })
        } else {
            let arr = []
            if (this.data.all_money == null) {
                arr = await this.getCouponsAlreadyGet(value)
            } else {
                arr = await this.getCouponsAlreadyGet(value, this.data.all_money)
            }
            this.setData({
                list: arr
            })
        }
    },

    showDialog(e: any) {
        console.log(e.target.dataset.info)
        this.setData({
            descObj: e.target.dataset.info.info
        })
        this.setData({ showRule: true })
    },

    closeDialog() {
        this.setData({ showRule: false })
    },

    async getCouponsAlreadyGet(type: string, use_money = null) {
        const { page, size } = this.data
        let data: any
        type = type + ''
        if (use_money == null) {
            data = await getAlreadyOwnedCoupons(type, page, size)
        } else {
            data = await getAlreadyOwnedCoupons(type, page, size, use_money)
        }
        console.log(data, use_money, '---getAlreadyOwnedCoupons')
        let arr: any = []
        if (data.error == 0) {
            data.data.forEach((item: any) => {
                const startTime = item.use_start_date.replace('T', ' ')
                const endTime = item.use_last_date.replace('T', ' ')
                const time = `${startTime}-${endTime}`
                arr.push({
                    id: item.ID,
                    num: item.coupon_money,
                    type: item.coupon_name,
                    title: item.coupon_ms,
                    number: item.coupon_money,
                    time,
                    info: {
                        desc: item.coupon_ms,
                        startTime: item.use_start_date.replace('T', ' '),
                        endTime: item.use_last_date.replace('T', ' '),
                        moneyStart: item.coupon_money_start,
                        num: item.coupon_money
                    }
                })
            })
        }
        this.setData({
            total: data.count
        })
        return arr
    },

    async getAccessCoupons(page: number, size: number) {
        const data: any = await getACouponAvailable(page, size)
        console.log(data, '---getACouponAvailable')
        let arr: any = []
        if (data.error == 0) {
            if (data.data) {
                data.data.forEach((item: any) => {
                    const startTime = item.use_start_date.replace('T', ' ')
                    const endTime = item.use_last_date.replace('T', ' ')
                    const time = `${startTime}-${endTime}`
                    arr.push({
                        isGet: false, // 是否已领取
                        id: item.ID,
                        num: item.coupon_money,
                        type: item.coupon_name,
                        title: item.coupon_ms,
                        receive: item.re_receive,
                        number: item.number,
                        time,
                        info: {
                            desc: item.coupon_ms,
                            startTime: item.start_time.replace('T', ' '),
                            endTime: item.end_date.replace('T', ' '),
                            moneyStart: item.coupon_money_start,
                            num: item.coupon_money
                        }
                    })
                })
            }
        }
        this.setData({
            total: data.count
        })
        return arr
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(option: any) {
        console.log(option, '---preferentialCenter.ts')
        // 用于判断是哪个页面进来的
        if (option.type) {
            this.setData({
                type: option.type,
                value: option.type * 1,
                all_money: option.all_money * 1
            })
        }
        if (this.data.value == 0) {
            const arr = await this.getAccessCoupons(this.data.page, this.data.size)
            this.setData({
                list: arr
            })
        } else {
            const arr = await this.getCouponsAlreadyGet(this.data.value, this.data.all_money)
            this.setData({
                list: arr,
                valueArr: [
                    {
                        label: '未使用',
                        value: 1
                    },
                    {
                        label: '已使用',
                        value: 2
                    },
                    {
                        label: '已失效',
                        value: 3
                    }
                ]
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        let { size, value } = this.data
        this.setData({
            page: 1,
            size: 5,
            isAll: false
        })
        if (value == 0) {
            const arr = await this.getAccessCoupons(1, size)
            this.setData({
                list: arr
            })
        } else {
            let arr = []
            if (this.data.all_money == null) {
                arr = await this.getCouponsAlreadyGet(value)
            } else {
                arr = await this.getCouponsAlreadyGet(value, this.data.all_money)
            }

            this.setData({
                list: arr
            })
        }

        //停止下拉刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    async onReachBottom() {
        let { page, size, list, total, value } = this.data
        if (page * size >= total) {
            wx.showToast({
                title: '到底啦～'
            })
            return
        }
        if (value == 0) {
            page = page + 1
            this.setData({
                page
            })
            const arr = await this.getAccessCoupons(page, size)
            console.log('触底啦', arr, page)
            this.setData({
                list: [...list, ...arr]
            })
        } else {
            page = page + 1
            this.setData({
                page
            })
            console.log('触底啦', page)
            let arr = []
            if (this.data.all_money == null) {
                arr = await this.getCouponsAlreadyGet(value)
            } else {
                arr = await this.getCouponsAlreadyGet(value, this.data.all_money)
            }

            if (arr.length < size) {
                this.setData({
                    isAll: true
                })
            }

            this.setData({
                list: [...list, ...arr]
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {}
})
